package diona.model.requests

import org.joda.time.format.{DateTimeFormatter, DateTimeFormat}
import org.apache.http.impl.client.DefaultHttpClient
import org.apache.http.entity.StringEntity
import xml._
import org.apache.http.client.methods.HttpPost
import net.liftweb.common.Logger

/**
 * User: anton
 * Date: 03.07.11 15:23
 */
object Solr extends Logger
{
  private val formatter: DateTimeFormatter = DateTimeFormat.forPattern("yyyy-mm-dd'T'HH:MM:SS.SSS'Z'")

  private val solrUrl = "http://localhost:8983/solr/update"

  @volatile var send: List[SolrPost] => Unit =
    posts => {
      posts match {
        case Nil => debug("Nothing to send for solr")
        case _ =>
          val request: Elem = <add>
            {for (post <- posts) yield
              <doc>
                <field name="id">{post.url}</field>
                <field name="url">{post.url}</field>
                <field name="content">{post.content}</field>
                <field name="title">{post.title}</field>
                <field name="tstamp">{formatter.print(post.tstamp)}</field>
                <field name="lang">{post.lang}</field>
                <field name="postType">{post.postType}</field>
                <field name="resultId">{post.resultId}</field>
                {for (tag <- post.tags) yield
                  <field name="tag">{tag}</field>
                }
              </doc>
            }
          </add>
          var client = new DefaultHttpClient()
          val update = new HttpPost(solrUrl)
          update.setEntity(new StringEntity(Utility.toXML(request).toString(), "application/xml", "utf-8"))
          client.execute(update)
          client = new DefaultHttpClient()
          val commit = new HttpPost(solrUrl)
          commit.setEntity(new StringEntity("<commit/>", "application/xml", "utf-8"))
          client.execute(commit)
      }
    }
}